<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
    <div class="g-drawer-list-container">
      <div class="g-drawer-progress-container">
        <TitleSecondary title="审批流程图" />
        <ProgressStaus />
      </div>
      <ProgressGraph :data="detail.nodeFlowChartList" />
      <TitleSecondary title="基本信息" />
      <FormBasicInfo :is-edit="false" :form="form" :plan-type="pageType" />
      <TitleSecondary title="销售责任人" />
      <TableSaleListSecondary
        :data-source="detail.mforecastSalesList"
        :page-type="pageType"
        style="margin-bottom: 20px"
      />
      <TitleSecondary title="FCST明细" />

      <p-tabs
        class="g-drawer-poros-tabs"
        :default-active-key="'1'"
        type="card"
        @change="handleTabChange"
      >
        <p-tab-pane key="1" :tab="'FCST'">
          <TablePlanDetail
            ref="table-detail"
            :data-source="planDetailList"
            :is-edit="false"
            :hide-keys="hasEdit ? [] : ['selection']"
            :active-tab="activeTab"
            :plan-id="planId"
            :mforecast-sales-id="detail.mforecastSalesId"
            :plan-sales="detail.mforecastSalesList"
            local-key="m9-saler-audit-first"
            :buttons="[
              {
                key: 'show',
                label: '显示字段',
              },
              {
                key: 'screenfull',
                label: '全屏显示',
              },
            ]"
            :time-range="[form.startTime, form.endTime]"
            :parent-id="form.salesOrganization"
            @checked="handleTableCheckedChange"
          />
        </p-tab-pane>
        <p-tab-pane key="2">
          <span slot="tab">总览</span>
          <TablePlanDetailTotal
            :data-source="totalDetailList"
            :plan-sales="detail.mforecastSalesList"
            :plan-id="planId"
            :plan-type="planType"
            :hide-keys="hasEdit ? [] : ['selection']"
            :active-tab="activeTab"
            :time-range="[form.startTime, form.endTime]"
            :plan-sales-id="detail.planSalesId"
            local-key="m9-saler-audit-first-total"
            @checked="handleTableCheckedChange"
          />
        </p-tab-pane>
      </p-tabs>
      <TitleSecondary v-if="hasEdit" title="审批信息" />
      <ApprovalInformation
        v-if="hasEdit"
        ref="approval"
        :disabled-agree="disabledAgree"
        :disabled-refuse="disabledRefuse"
      />
      <ProgressLog :list="logList" />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
    <DialogTransfer
      :visible.sync="visibleTransfer"
      :plan-id="planId"
      @change="onClose"
    />
  </p-drawer>
</template>

<script>
import FormBasicInfo from './FormBasicInfo.vue';
import TableSaleListSecondary from './TableSaleListSecondary.vue';
import ProgressGraph from '@/components/task/ProgressGraph.vue';
import ProgressLog from '@/components/task/ProgressLog.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
import TablePlanDetail from './TablePlanDetail.vue';
import ApprovalInformation from '@/components/task/ApprovalInformation.vue';
import DialogTransfer from '@/components/dialog/DialogTransferForecast.vue';

import { postSaleDirectorApprove } from '@/api/forecast';
import DrawerMixin from './mixin';

export default {
  components: {
    FormBasicInfo,
    TablePlanDetail,
    TableSaleListSecondary,
    ProgressGraph,
    ProgressLog,
    ProgressStaus,
    ApprovalInformation,
    DialogTransfer,
  },

  mixins: [DrawerMixin],

  data() {
    return {
      planDetailList: [],
      visibleTransfer: false,
      checkedGroups: {},
      groups: {},
    };
  },
  computed: {
    disabledAgree() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      const groupsLenght = Object.keys(this.groups).length;
      if (checkedLength === 0) return true;
      return checkedLength !== groupsLenght;
    },
    disabledRefuse() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      return checkedLength < 1;
    },
    isShowProgressPortrait() {
      return this.iconStaus === 'up';
    },
    form() {
      return this.detail.plan || {};
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  methods: {
    handleTableCheckedChange(checkedGroups, groups) {
      this.checkedGroups = checkedGroups;
      this.groups = groups;
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      const data = this.$refs.approval?.form || {};
      if (typeof data.approveStatus !== 'boolean') {
        this.$message.error('请先进行审批！');
        return;
      }
      if (data.approveStatus === false && !data.approveOpinion) {
        this.$message.error('请填写审批意见！');
        return;
      }
      if (data.approveStatus === true && this.disabledAgree) {
        this.$message.error('明细表未选择全部！');
        return;
      }
      if (data.approveStatus === false && this.disabledRefuse) {
        this.$message.error('请至少选择一条数据');
        return;
      }

      const formatData = {
        handleResult: data.approveStatus ? 0 : 1,
        handleRemark: data.approveOpinion,
        makeCopy: data.makeCopy,
      };

      const checkedGroupsIds = Object.keys(this.checkedGroups).reduce(
        (pre, cur) => {
          if (this.checkedGroups[cur]) {
            pre.push(cur);
          }
          return pre;
        },
        []
      );
      const rejectList = data.approveStatus ? undefined : checkedGroupsIds;
      await postSaleDirectorApprove({
        ...formatData,
        mforecastId: this.planId,
        rejectList,
      });

      this.$message.success('提交成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
